package bootstrap

import (
	"github.com/kataras/golog"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"io"
	"ntrace/utils/times"
	"os"
	"strings"
	"time"
)

// InitLogger 初始化logger
func InitLogger(fileName string, maxAgeHour time.Duration) []*rotatelogs.RotateLogs {
	golog.SetTimeFormat(times.TimeFmt)
	if fileName == "" {
		golog.SetOutput(os.Stdout)
		return nil
	}

	var logs []*rotatelogs.RotateLogs
	aggrLog := fileName + ".%Y%m%d"
	if strings.HasSuffix(fileName, ".log") {
		aggrLog = strings.TrimSuffix(fileName, ".log") + "-%Y%m%d.log"
	}

	w, err := rotatelogs.New(
		aggrLog,
		rotatelogs.WithLinkName(fileName),
		rotatelogs.WithMaxAge(maxAgeHour*time.Hour),
		rotatelogs.WithRotationTime(24*time.Hour),
		rotatelogs.WithRotationSize(500*1024*1024),
		rotatelogs.WithRotationCount(10))
	if err != nil {
		panic(err)
	}

	multiWriter := io.MultiWriter(os.Stdout, w)
	golog.SetOutput(multiWriter)

	logs = append(logs, w)
	return logs
}
